package ntu.metaweb.http;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.HashMap;

import rice.Continuation;
import ntu.metaweb.Metaweb;
import ntu.metaweb.XMLMarshaller;
import ntu.metaweb.result.Comments;
import ntu.metaweb.service.Service;
import ntu.metaweb.storage.WebPage;
import ntu.metaweb.storage.WebPageKey;
import ntu.p2p.dht.DHTContent;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;

@SuppressWarnings("restriction")
public class GetCommentsHandler implements CommandHandler {

	@Override
	public void handleCommand(final HttpExchange exchange,
			final HashMap<String, String> params) throws IOException {
		final WebPageKey key = 
				new WebPageKey(URLDecoder.decode(params.get("url"), "UTF-8"));
		Metaweb.getInstance().getDhtApplication().lookup(key, 
				new Continuation<DHTContent,Exception>() {

					@Override
					public void receiveException(Exception exception) {
						// create and insert web page object
						System.out.println("insert web page");
						try {
							URL url = new URL(URLDecoder.decode(params.get("url"), "UTF-8"));
							WebPage webpage = new WebPage(
									new WebPageKey(URLDecoder.decode(params.get("url"), "UTF-8")), url);
							Service.insertWebPage(webpage);
						} catch (UnsupportedEncodingException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (MalformedURLException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}

					@Override
					public void receiveResult(DHTContent result) {
						onReceiveResult(exchange, result);
					}
		});
	}

	protected void onReceiveResult(HttpExchange exchange, DHTContent result) {
		System.out.println("on receive result");
		WebPage webpage = (WebPage) result;
		Comments comments = new Comments(webpage);
		byte[] temp = XMLMarshaller.getInstance().marshall(comments).getBytes();
		System.out.println(XMLMarshaller.getInstance().marshall(comments));

		try {
			Headers responseHeaders = exchange.getResponseHeaders();
			responseHeaders.set("Content-Type", "text/xml");

			exchange.sendResponseHeaders(200, 0);

			OutputStream responseBody = exchange.getResponseBody();
			responseBody.write(temp);
			responseBody.close();
			exchange.close();
			System.out.println("close get comment handler");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
